
#If Not (PocketPC OrElse Smartphone) Then
Public Module consoleCancelKeyHandle

    Private _consoleExtSignal As Boolean = False
    Private _registerConsoleExtHandle As Boolean = False
    Private _consoleExtHandleFinish As Boolean = False
    Public Event consoleCancelKeyEvent(ByRef consoleExtHandleFinish As Boolean)

    'this line is important, if directly use local variable, will be re-allocate by GC
    Private handler As ConsoleCtrlDelegate = AddressOf ConsoleCtrlHandle

    Private Sub waitConsoleExtHandleFinish()
        While Not _consoleExtHandleFinish
            System.Windows.Forms.Application.DoEvents()
            sleep(64)
        End While
    End Sub

    Private Function ConsoleCtrlHandle(ByVal dwCtrlType As Int32) As Boolean
        _consoleExtSignal = True
        If _registerConsoleExtHandle Then
            waitConsoleExtHandleFinish()
            RaiseEvent consoleCancelKeyEvent(_consoleExtHandleFinish)
            waitConsoleExtHandleFinish()
        End If
        GC.KeepAlive(handler)
        Return True
    End Function

    Public Function consoleCancelKeyPressed() As Boolean
        Return _consoleExtSignal
    End Function

    Public Function consoleExtSignal() As Boolean
        Return consoleCancelKeyPressed()
    End Function

    Public Sub registerConsoleExtHandle(Optional ByVal eventHandler As consoleCancelKeyEventEventHandler = Nothing)
        If Not SetConsoleCtrlHandler(handler, True) Then
            raiseError("cannot SetConsoleCtrlHandler, may miss console events.", errorHandle.errorType.exclamation)
        Else
            _registerConsoleExtHandle = True
            If Not eventHandler Is Nothing Then
                AddHandler consoleCancelKeyEvent, eventHandler
            End If
        End If
    End Sub

    Public Sub consoleExtHandleFinish()
        _consoleExtHandleFinish = True
    End Sub

End Module
#End If
